const crypto = require('crypto');
const axios = require('axios');
const { Payment, User, MaterialOrder } = require('../models');
const config = require('../config/payment');

// 生成订单号
const generateOrderId = () => {
  const timestamp = Date.now().toString();
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  return `ORDER${timestamp}${random}`;
};

// 创建支付订单
const createPaymentOrder = async (userId, amount, coins, paymentMethod, materialOrderId = null) => {
  try {
    // 验证用户是否存在（如果有用户ID）
    if (userId) {
      const user = await User.findByPk(userId);
      if (!user) {
        throw new Error('用户不存在');
      }
    }

    // 创建订单记录
    const orderId = generateOrderId();
    const notifyUrl = `${config.baseUrl}/api/payment/notify`;
    const returnUrl = `${config.baseUrl}/payment/result`;

    const payment = await Payment.create({
      orderId,
      userId,
      amount,
      coins,
      paymentMethod,
      status: 'pending',
      notifyUrl,
      returnUrl,
      materialOrderId
    });

    // 这里应该调用实际的支付网关API
    // 目前仅返回模拟数据
    const paymentUrl = `${config.baseUrl}/pay?orderId=${orderId}`;

    return {
      success: true,
      orderId: payment.orderId,
      paymentUrl,
      amount: payment.amount,
      coins: payment.coins
    };
  } catch (error) {
    console.error('创建支付订单失败:', error);
    throw error;
  }
};

// 处理支付回调
const handlePaymentCallback = async (orderId, paymentId, status, callbackData) => {
  try {
    const payment = await Payment.findOne({
      where: { orderId }
    });

    if (!payment) {
      throw new Error('订单不存在');
    }

    if (payment.status === 'paid') {
      return { success: true, message: '订单已处理' };
    }

    // 更新支付状态
    await payment.update({
      status: status,
      paymentId: paymentId,
      callbackData: JSON.stringify(callbackData)
    });

    if (status === 'paid') {
      // 如果是充值金币，更新用户金币
      if (payment.coins > 0 && payment.userId) {
        const user = await User.findByPk(payment.userId);
        if (user) {
          await user.update({
            coins: user.coins + payment.coins
          });
        }
      }

      // 如果是材料订单，更新订单状态
      if (payment.materialOrderId) {
        const materialOrder = await MaterialOrder.findByPk(payment.materialOrderId);
        if (materialOrder) {
          await materialOrder.update({ status: 'completed' });
        }
      }
    }

    return { success: true, message: '支付状态更新成功' };
  } catch (error) {
    console.error('处理支付回调失败:', error);
    throw error;
  }
};

// 查询支付订单状态
const queryPaymentStatus = async (orderId) => {
  try {
    const payment = await Payment.findOne({
      where: { orderId },
      include: [
        {
          model: User,
          attributes: ['username', 'email']
        },
        {
          model: MaterialOrder,
          include: [{
            model: Material,
            attributes: ['id', 'title', 'price']
          }]
        }
      ]
    });

    if (!payment) {
      throw new Error('订单不存在');
    }

    return {
      success: true,
      orderId: payment.orderId,
      status: payment.status,
      amount: payment.amount,
      coins: payment.coins,
      paymentMethod: payment.paymentMethod,
      createdAt: payment.createdAt,
      user: payment.user ? {
        username: payment.user.username,
        email: payment.user.email
      } : null
    };
  } catch (error) {
    console.error('查询支付状态失败:', error);
    throw error;
  }
};

// 获取用户支付记录
const getUserPayments = async (userId, page = 1, limit = 10) => {
  try {
    const offset = (page - 1) * limit;
    
    const { count, rows } = await Payment.findAndCountAll({
      where: { userId },
      order: [['createdAt', 'DESC']],
      limit,
      offset,
      include: [{
        model: User,
        attributes: ['username', 'email']
      }]
    });

    const payments = rows.map(payment => ({
      orderId: payment.orderId,
      amount: payment.amount,
      coins: payment.coins,
      status: payment.status,
      paymentMethod: payment.paymentMethod,
      createdAt: payment.createdAt,
      user: payment.user ? {
        username: payment.user.username,
        email: payment.user.email
      } : null
    }));

    return {
      success: true,
      payments,
      pagination: {
        total: count,
        page,
        limit,
        totalPages: Math.ceil(count / limit)
      }
    };
  } catch (error) {
    console.error('获取用户支付记录失败:', error);
    throw error;
  }
};

module.exports = {
  createPaymentOrder,
  handlePaymentCallback,
  queryPaymentStatus,
  getUserPayments
};